<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    :paddBottom="5"
  >
    <aps-form
      :config="apsForm.formConfig"
      :model="apsForm.formData"
      :formRef="apsForm.formRef"
      :labelWidth="apsForm.labelWidth"
      ref="form"
    ></aps-form>
    <lb-table
      :column="tableData.column"
      :data="tableData.data"
      border
      :height="600"
      pagination
      background
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[20, 40, 60, 80]"
      :pager-count="5"
      :current-page.sync="currentPage"
      :total="total"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @p-current-change="handleCurrentChange"
    >
    </lb-table>
    <component
      :is="modelName"
      :id="id"
      :visible.sync="show"
      :disabledFalge="disabledFalge"
      :title="opTitle"
      @close="close"
    ></component>
  </lb-layout>
</template>

<script>
import { listRole, changeStatus, delRole } from "@/api/auth/index.js";
import auth from "@/plugins/auth";
import operate from "@/views/configuration/organization/auth/components/operate.vue";
import datascope from "@/views/configuration/organization/auth/components/datascope.vue";
export default {
  name: "",
  components: {
    operate,
    datascope,
  },
  dicts: ["sys_normal_disable"],
  data() {
    return {
      //弹窗
      id: "",
      modelName: "",
      show: false,
      disabledFalge: false,
      opTitle: "",
      apsForm: {
        formRef: "form",
        labelWidth: "auto",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            roleName: {
              label: "角色名称:",
              typeName: "el-input",
              placeholder: "请输入角色名称",
            },
            remark: {
              label: "角色说明:",
              typeName: "el-input",
              placeholder: "请输入角色说明",
            },
            /* 普通或者字典下拉框 */
            status: {
              label: "角色状态:",
              render: (h) => {
                let that = this;
                let arr = [];
                that.dict?.type?.sys_normal_disable.some((item) => {
                  arr.push(item);
                });
                // 数据严谨处理,处理后端数据异常情况
                let valNum = that.$refs?.form?.getFieldsValue().status;
                let a = [
                  h(
                    "el-select",
                    {
                      attrs: {
                        placeholder: "请选择角色状态",
                        value: valNum,
                        clearable: true,
                      },
                      props: ["value"],
                      on: {
                        change: (value) => {
                          that.$refs?.form?.setFieldValue("status", value);
                          that.$forceUpdate();
                        },
                      },
                    },
                    [
                      arr.map((item) => {
                        let { label, value } = item;
                        return h("el-option", {
                          props: {
                            label,
                            value: value,
                            key: value,
                          },
                        });
                      }),
                    ]
                  ),
                ];
                return h("div", a);
              },
            },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleReset,
            },
            {
              label: "新增角色",
              type: "primary",
              typeName: "el-button",
              display: true,
              plain: true,
              size: "small",
              icon: "el-icon-plus",
              click: () => this.showModel("operate", null, false, "新建角色"),
            },
          ],
        },
      },
      currentPage: 1,
      pageSize: 20,
      total: 0,
      tableData: {
        column: [
          {
            prop: "roleName",
            label: "角色名称",
            // minWidth: 120,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "remark",
            label: "角色说明",
            // minWidth: 120,
            align: "center",
            showOverflowTooltip: true,
          },
          {
            prop: "status",
            label: "角色状态",
            width: 160,
            align: "center",
            showOverflowTooltip: true,
            render: (h, scope) => {
              let that = this;
              let activeStyle = {
                color: "#74BE80",
                marginLeft: "10px",
              };
              let inactiveStyle = {
                color: "#E65D6E",
                marginRight: "10px",
              };
              let a, active, inactive;
              if (
                scope.row.roleId == 1 ||
                scope.row.roleKey == "cockpit_leader"
              ) {
                a = <span></span>;
                active = <span></span>;
                inactive = <span></span>;
              } else {
                active = <span style={activeStyle}>正常</span>;
                inactive = <span style={inactiveStyle}>停用</span>;
                a = (
                  <el-switch
                    v-model={scope.row.status}
                    active-value={"0"}
                    inactive-value={"1"}
                    size="small"
                    onChange={() => {
                      if (auth.hasPermi("system:role:edit")) {
                        that.handleStatusChange(scope.row);
                      } else {
                        that.$message.error("你未有改变角色状态的权限");
                      }
                    }}
                  ></el-switch>
                );
              }
              return (
                <div>
                  {inactive}
                  {a}
                  {active}
                </div>
              );
            },
          },
          {
            prop: "dataScope",
            label: "数据权限类型",
            width: 120,
            render: (h, scope) => {
              let arr = [
                {
                  value: "1",
                  label: "全部数据权限",
                },
                {
                  value: "2",
                  label: "自定数据权限",
                },
                {
                  value: "3",
                  label: "本部门数据权限",
                },
                {
                  value: "4",
                  label: "本部门及以下数据权限",
                },
                {
                  value: "5",
                  label: "仅本人数据权限",
                },
              ];
              let a = "";
              arr.map((item) => {
                if (item.value == scope.row.dataScope) {
                  a = item.label;
                }
              });
              return <div>{a}</div>;
            },
          },
          {
            prop: "",
            label: "数据授权",
            width: 100,
            render: (h, scope) => {
              let that = this;
              let a;
              if (
                scope.row.roleId == 1 ||
                scope.row.roleKey == "cockpit_leader"
              ) {
                a = <span></span>;
              } else {
                a = (
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-setting"
                    v-hasPermi={["system:role:edit"]}
                    onClick={() => {
                      that.showModel("datascope", scope.row);
                    }}
                  >
                    授权
                  </el-button>
                );
              }
              return <div>{a}</div>;
            },
          },
          {
            label: "驾驶舱授权内容",
            width: 140,
            render: (h, scope) => {
              let that = this;
              let a;
              if (
                scope.row.roleId == 1 ||
                scope.row.roleKey == "cockpit_leader"
              ) {
                a = <span></span>;
              } else {
                a = (
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-view"
                    v-hasPermi={["system:role:query"]}
                    onClick={() => {
                      that.$router.push({
                        name: "authorSet2",
                        query: {
                          roleId: scope.row.roleId,
                          disabled: "1",
                        },
                      });
                    }}
                  >
                    详情
                  </el-button>
                );
              }
              return <div>{a}</div>;
            },
          },
          {
            label: "WEB端授权内容",
            width: 140,
            render: (h, scope) => {
              let that = this;
              let a;
              if (
                scope.row.roleId == 1 ||
                scope.row.roleKey == "cockpit_leader"
              ) {
                a = <span></span>;
              } else {
                a = (
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-view"
                    v-hasPermi={["system:role:query"]}
                    onClick={() => {
                      that.$router.push({
                        name: "authorSet",
                        query: {
                          roleId: scope.row.roleId,
                          disabled: "1",
                        },
                      });
                    }}
                  >
                    详情
                  </el-button>
                );
              }
              return <div>{a}</div>;
            },
          },
          {
            label: "驾驶舱端授权",
            width: 120,
            render: (h, scope) => {
              let that = this;
              let a;
              if (
                scope.row.roleId == 1 ||
                scope.row.roleKey == "cockpit_leader"
              ) {
                a = <span></span>;
              } else {
                a = (
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-setting"
                    v-hasPermi={["system:role:edit"]}
                    onClick={() => {
                      that.$router.push({
                        name: "authorSet2",
                        query: {
                          roleId: scope.row.roleId,
                          disabled: "0",
                        },
                      });
                    }}
                  >
                    设置权限
                  </el-button>
                );
              }
              return <div>{a}</div>;
            },
          },
          {
            label: "WEB端授权",
            width: 120,
            render: (h, scope) => {
              let that = this;
              let a;
              if (
                scope.row.roleId == 1 ||
                scope.row.roleKey == "cockpit_leader"
              ) {
                a = <span></span>;
              } else {
                a = (
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-setting"
                    v-hasPermi={["system:role:edit"]}
                    onClick={() => {
                      that.$router.push({
                        name: "authorSet",
                        query: {
                          roleId: scope.row.roleId,
                          disabled: "0",
                        },
                      });
                    }}
                  >
                    设置权限
                  </el-button>
                );
              }
              return <div>{a}</div>;
            },
          },
          // {
          //   prop: "subApplication",
          //   label: "字典字段",
          //   minWidth: 120,
          //   align: "center",
          //   showOverflowTooltip: true,
          //   render: (h, scope) => {
          //     return (
          //       <div>
          //         <dict-tag
          //           options={this.dict.type.sys_normal_disable}
          //           value={scope.row.subApplication}
          //         />
          //       </div>
          //     );
          //   },
          // },
          {
            label: "操作",
            width: 260,
            fixed: "right",
            render: (h, scope) => {
              let that = this;
              let a, b, c;
              a = (
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-view"
                  v-hasPermi={["system:role:list"]}
                  onClick={() => {
                    that.$router.push({
                      name: "authUserlist",
                      params: {
                        roleId: scope.row.roleId,
                      },
                    });
                  }}
                >
                  用户分配
                </el-button>
              );
              if (
                scope.row.roleId == 1 ||
                scope.row.roleKey == "cockpit_leader"
              ) {
                b = <span></span>;
                c = <span></span>;
              } else {
                b = (
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-edit"
                    v-hasPermi={["system:role:edit"]}
                    onClick={() => {
                      that.showModel("operate", scope.row, true, "编辑角色");
                    }}
                  >
                    编辑
                  </el-button>
                );
                c = (
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-delete"
                    v-hasPermi={["system:role:remove"]}
                    onClick={() => {
                      that.handlerDelete(scope.row);
                    }}
                    class="text-danger"
                  >
                    删除
                  </el-button>
                );
              }
              return (
                <div>
                  {a}
                  {b}
                  {c}
                </div>
              );
            },
          },
        ],
        data: [],
      },
    };
  },
  created() {},
  mounted() {
    this.judgePermi();
    this.handlerSearchDetail();
  },
  methods: {
    judgePermi() {
      if (auth.hasPermi("system:role:add")) {
        this.apsForm.formConfig.formSoltButton[2].display = false;
      }
    },
    async initData(data) {
      let that = this;
      let query = {
        ...data,
      };
      query.pageNum = that.currentPage;
      query.pageSize = that.pageSize;
      that.$store.commit("app/updateApiCount", "add");
      await listRole(query)
        .then((res) => {
          that.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          that.tableData.data = res?.rows ?? [];
          that.total = res?.total ?? 0;
        })
        .catch((err) => {
          that.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    // 搜索
    handlerSearchDetail() {
      const { ...other } = this.$refs?.form?.getFieldsValue();
      const data = {
        ...other,
      };
      this.initData(data);
    },
    // 重置
    handleReset() {
      this.$refs?.form?.resetFields();
      this.handlerSearchDetail();
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    handleStatusChange(row) {
      let query = {
        roleId: row.roleId,
        status: row.status,
      };
      changeStatus(query)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.handlerSearchDetail();
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    handlerDelete(row) {
      let that = this;
      let id = row.roleId;
      const text = "是否确认删除" + (row?.name ?? "该条数据") + "？";
      this.$modal
        .confirm(text)
        .then(() => {
          that.delectRequest(id);
        })
        .catch(() => {
          that.$message({
            message: "取消删除",
          });
        });
    },
    delectRequest(id) {
      let that = this;
      delRole(id)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          that.$message.success("已删除!");
          that.handlerSearchDetail();
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!");
        });
    },
    // 弹窗
    showModel(name, params, falge, title) {
      this.modelName = name;
      this.id = params?.roleId || "";
      this.disabledFalge = falge ?? false;
      this.opTitle = title ?? "";
      setTimeout(() => {
        this.show = true;
      }, 200);
    },
    close(status) {
      this.show = false;
      setTimeout(() => {
        if (status) this.handlerSearchDetail();
      }, 200);
    },
  },
};
</script>

<style lang="scss" scoped></style>
